package edu.je.column.interceptor;

import com.junqson.je.common.UserHolder;
import com.junqson.je.common.annotation.LoginRequire;
import com.junqson.je.common.constant.AppConstant;
import com.junqson.je.common.constant.AppRedisKey;
import com.junqson.je.common.exception.BizException;
import com.junqson.je.common.model.ResultEnum;
import com.junqson.je.common.model.User;
import com.junqson.je.common.util.AppUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @Descriptions
 * @Company
 * @Author Junqson
 * @Date 2020/1/30 18:10
 * @Version 1.0
 */
@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        Method method = ((HandlerMethod) handler).getMethod();

        // 判断需要调用需要登陆的接口时是否已经登陆
        boolean isLoginRequired = isAnnotationPresent(method, LoginRequire.class);
        if (isLoginRequired) {

            // 获取用户上下文
            String userId = request.getHeader(AppConstant.UID_HEADER);
            if (StringUtils.isEmpty(userId)) {
                throw new BizException(ResultEnum.NEED_LOGIN);
            }

            String userK = AppUtil.getRedisKey(AppRedisKey.USER_CACHE, userId);

            Object userObj = redisTemplate.opsForValue().get(userK);
            if (userObj == null) {
                throw new BizException(ResultEnum.NEED_LOGIN);
            }

            User user = (User) userObj;

            LoginRequire annotation = method.getAnnotation(LoginRequire.class);
            boolean needAuth = annotation.needAuth();

            if (needAuth && !user.isAuthenticated()) {
                throw new BizException(ResultEnum.NEED_AUTH);
            }

            UserHolder.set(user);

            log.info("userId: [{}], need-auth: [{}]", userId, needAuth);

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserHolder.remove();
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    public boolean isAnnotationPresent(Method method, Class<? extends Annotation> annotationClass) {
        //  类注解或方法注解
        return method.isAnnotationPresent(annotationClass);
    }

}
